package rattlesnake.callback.config.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rattlesnake.callback.config.constant.CallBackConstant;
import rattlesnake.callback.util.CodecUtil;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @Package: rattlesnake.callback.config.filter
 * @Description: 进行消息过滤
 * @author: liuxin
 * @date: 17/4/10 下午3:19
 */
public class MessageFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(MessageFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.debug("================MyFilter start================");
    }

    /**
     * 当第一次进入会根据根据参数计算摘要，并保存，由不通的渠道进行去重校验
     * key=value&key=value 生成摘要MessageCode
     * 根据url规则获得服务品类生成CacheName
     * 校验部分交给拦截器处理
     * @param request
     * @param response
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     *
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        Enumeration<String> keys = request.getParameterNames();
        request.getRemoteHost();
        StringBuffer sb = new StringBuffer();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String value = request.getParameter(key);
            sb.append(key).append("=").append(value).append("&");
        }
        String message = sb.substring(0, sb.length() - 1);
        logger.debug("参数:{}", message);
        request.setAttribute(CallBackConstant.MESSAGECODE, CodecUtil.encryptMD5(message));
        String url = ((HttpServletRequest) request).getRequestURI();
        String [] channel=url.split("/");
        logger.debug("请求地址:{},缓存名称:{}",url,channel[2]);
        request.setAttribute(CallBackConstant.CACHENAME,channel[2]);
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        logger.debug("================MyFilter destroy================");
    }
}
